import { joinUser, transformUser } from './helper'
import { randTime, uuid } from '@/utils'
import { PAGE_SIZES } from '@/constant/modules/paging'
import type { TableColumn, Team } from '@/types'

import { schedulingApi } from '@/api'

function getTeamLists(params: {
  pageNumber: number
  pageSize: number
}) {
  const { pageNumber = 1, pageSize = 10 } = params || {}
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve([
        ...Array(pageSize)
          .fill(1)
          .map((_v, i) => {
            const id = (pageNumber - 1) * pageSize + i + 1
            return {
              id,
              name: `班组名称${id}`,
              creationTime: randTime(),
              creatorUserId: 10,
              creatorUserName: '张飞',
              creatorLoginName: 'zhangfei',
              updateTime: randTime(),
              updateUserId: 10,
              updatorUserName: '张飞',
              updatorLoginName: 'zhangfei',
            }
          }),
      ])
    }, 600)
  })
}

function transfer(data: any[]): Team[] {
  return data.map(v => ({
    id: v.id,
    name: v.name,
    ...transformUser(v),
  }))
}

export function useTeamLists() {
  const [loading, setLoading] = useState(true)
  const pagination = reactive({
    pageNumber: 1,
    pageSize: PAGE_SIZES[0]!,
    total: 0,
  })
  const columns: TableColumn<Team>[] = reactive([
    { key: uuid(), label: '班组名称', prop: 'name' },
    { key: uuid(), label: '创建时间', prop: 'creationTime' },
    {
      key: uuid(),
      label: '创建人',
      prop: 'creatorUserName',
      render({ row }) {
        return h('span', joinUser(row.creatorUserName, row.creatorLoginName))
      },
    },
    { key: uuid(), label: '修改时间', prop: 'updateTime' },
    {
      key: uuid(),
      label: '修改人',
      prop: 'updatorUserName',
      render({ row }) {
        return h('span', joinUser(row.updatorUserName, row.updatorLoginName))
      },
    },
  ])
  const [lists, setLists] = useShallowState<Team[]>([])

  async function getLists(params: Record<string, string> = {}) {
    setLoading(true)
    try {
      const { data } = await schedulingApi.selectTeamPage({
        ...params,
        pageNumber: pagination.pageNumber,
        pageSize: pagination.pageSize,
      })
      setLists(transfer(data.records || []))
      pagination.total = data.total
    }
    catch (e) {
    }
    finally {
      setLoading(false)
    }
  }

  return {
    loading,
    pagination,
    columns,
    lists,
    setLists,
    getLists,
  }
}
